#pragma once
#include <vector>
#include "UdpSocket.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"

namespace RouteModule
{
    using namespace UdpSocketModule;
    using namespace LogModule;
    using namespace InetAddrModule;
    class Route
    {
    private:
        void AddChatUser(InetAddr newuser)
        {
            LOG(LogLevel::INFO) << "用户" << newuser.PrintDebug() << "添加成功！";
            _chatuser.push_back(newuser);
        }

        void DisplayChatUser()
        {
            LOG(LogLevel::INFO) << "--------user table-------";
            for(auto& x: _chatuser)
            {
                LOG(LogLevel::INFO) << x.PrintDebug();
            }
            LOG(LogLevel::INFO) << "-------------------------";
        }

        void DelChatUser(InetAddr olduser)
        {
            for (auto it = _chatuser.begin(); it != _chatuser.end();)
            {
                if (*it == olduser)
                {
                    it = _chatuser.erase(it); // ✅ erase 返回下一个有效迭代器
                }
                else
                {
                    ++it;
                }
            }
        }

        bool FindChatUser(InetAddr user)
        {
            for (auto &x : _chatuser)
            {
                if (x == user)
                {
                    return true;
                }
            }
            return false;
        }

    public:
        Route()
        {}
        void HandlerChat(UdpSocket& sock, const std::string& msg, InetAddr& user)
        {
            if (!FindChatUser(user))
            {
                AddChatUser(user);
                DisplayChatUser();
            }
            LOG(LogLevel::INFO) << "用户" << user.PrintDebug() << "请求转发消息：" << msg;
            std::string message = msg;
            message =  user.PrintDebug() + message;
            for (auto &usr : _chatuser)
            {
                sock.Sendto(message, usr.Port(), usr.Ip());
            }
        }

    private:
        std::vector<InetAddr> _chatuser;
    };
}
